<template>
  <div class="chat-container">
    <!-- 聊天头部 -->
    <div class="chat-header">
      <div class="header-content">
        <i class="el-icon-chat-dot-round"></i>
        <span>健康信息专家</span>
      </div>
      <div class="connection-status" :class="{ 'connected': isConnected }">
        {{ isConnected ? '已连接' : '连接中...' }}
      </div>
    </div>

    <!-- 聊天内容区域 -->
    <div class="chat-content" ref="chatContent">
      <div v-for="(message, index) in messages" :key="index">
        <!-- 日期分隔条 -->
        <div v-if="shouldShowDate(index)" class="date-divider">
          {{ message.date }}
        </div>
        <div :class="['message-wrapper', message.type === 'user' ? 'user-message' : 'ai-message']">
          <div class="message-avatar">
            <i :class="message.type === 'user' ? 'el-icon-user' : 'el-icon-s-custom'"></i>
          </div>
          <div class="message-content">
            <div class="message-text" v-html="formatMessage(message.content)"></div>
            <div class="message-time">{{ message.time }}</div>
          </div>
        </div>
      </div>
      <!-- 正在输入提示 -->
      <div v-if="isTyping" class="message-wrapper ai-message">
        <div class="message-avatar">
          <i class="el-icon-s-custom"></i>
        </div>
        <div class="message-content">
          <div class="typing-indicator">
            <span></span>
            <span></span>
            <span></span>
          </div>
        </div>
      </div>
    </div>

    <!-- 输入区域 -->
    <div class="chat-input">
      <el-input
        v-model="inputMessage"
        type="textarea"
        :rows="3"
        placeholder="请输入您的问题..."
        resize="none"
        @keyup.enter.native="sendMessage"
      ></el-input>
      <el-button 
        type="primary" 
        :disabled="!inputMessage.trim() || !isConnected"
        @click="sendMessage"
      >
        发送
        <i class="el-icon-s-promotion"></i>
      </el-button>
    </div>
  </div>
</template>

<script>
import request from '@/utils/request'
export default {
  name: 'Chat',
  data() {
    return {
      ws: null,
      isConnected: false,
      messages: [],
      inputMessage: '',
      isTyping: false,
      reconnectAttempts: 0,
      maxReconnectAttempts: 5,
      reconnectInterval: 3000
    }
  },
  created() {
    this.fetchHistory();
    this.initWebSocket();
  },
  beforeDestroy() {
    this.closeWebSocket();
  },
  methods: {
    async fetchHistory() {
      try {
        const res = await request({
          url: '/chatHistory',
          method: 'get'
        });
        if (res.code === 200 && Array.isArray(res.data)) {
          // 按照createTime从小到大排序
          const sortedData = res.data.sort((a, b) => new Date(a.createTime) - new Date(b.createTime));
          sortedData.forEach(item => {
            // 解析question字段，假设格式为{"content":"xxx"}
            let questionContent = '';
            try {
              const questionObj = JSON.parse(item.question);
              questionContent = questionObj.content || '';
            } catch (e) {
              questionContent = item.question;
            }
            // 添加用户消息
            this.messages.push({
              content: questionContent,
              type: 'user',
              time: new Date(item.createTime).toLocaleTimeString(),
              date: new Date(item.createTime).toLocaleDateString()
            });
            // 添加AI消息
            this.messages.push({
              content: item.answer,
              type: 'ai',
              time: new Date(item.createTime).toLocaleTimeString(),
              date: new Date(item.createTime).toLocaleDateString()
            });
          });
          this.$nextTick(() => {
            this.scrollToBottom();
          });
        }
      } catch (e) {
        this.$message.error('获取历史消息失败');
      }
    },
    initWebSocket() {
      const token = this.getCookie('Admin-Token')
      if (!token) {
        this.$message.error('未登录，请先登录')
        return
      }

      const wsUrl = `ws://47.110.138.104:8080/jkgl/GptSocket?Authorization=${encodeURIComponent(token)}`
      this.ws = new WebSocket(wsUrl)

      this.ws.onopen = () => {
        console.log('WebSocket连接已建立')
        this.isConnected = true
        this.reconnectAttempts = 0
        this.addSystemMessage('连接成功，开始对话吧！')
      }

      this.ws.onmessage = (event) => {
        this.isTyping = false;
        // 直接使用返回的字符串作为AI消息内容
        this.addMessage(event.data, 'ai');
      }

      this.ws.onerror = (error) => {
        console.error('WebSocket错误:', error)
        this.isConnected = false
      }

      this.ws.onclose = () => {
        console.log('WebSocket连接已关闭')
        this.isConnected = false
        this.handleReconnect()
      }
    },

    handleReconnect() {
      if (this.reconnectAttempts < this.maxReconnectAttempts) {
        this.reconnectAttempts++
        this.addSystemMessage(`连接断开，正在尝试重新连接...(${this.reconnectAttempts}/${this.maxReconnectAttempts})`)
        setTimeout(() => {
          this.initWebSocket()
        }, this.reconnectInterval)
      } else {
        this.addSystemMessage('连接失败，请刷新页面重试')
      }
    },

    closeWebSocket() {
      if (this.ws) {
        this.ws.close()
      }
    },

    sendMessage() {
      if (!this.inputMessage.trim() || !this.isConnected) return;
      const message = this.inputMessage.trim();
      this.addMessage(message, 'user');
      this.isTyping = true;
      try {
        this.ws.send(JSON.stringify({
          content: message
        }));
        this.inputMessage = '';
      } catch (error) {
        console.error('发送消息失败:', error);
        this.addSystemMessage('发送消息失败，请重试');
      }
    },

    addMessage(content, type) {
      this.messages.push({
        content,
        type,
        time: new Date().toLocaleTimeString(),
        date: new Date().toLocaleDateString()
      })
      this.$nextTick(() => {
        this.scrollToBottom()
      })
    },

    addSystemMessage(content) {
      this.messages.push({
        content,
        type: 'system',
        time: new Date().toLocaleTimeString(),
        date: new Date().toLocaleDateString()
      })
      this.$nextTick(() => {
        this.scrollToBottom()
      })
    },

    scrollToBottom() {
      const container = this.$refs.chatContent
      container.scrollTop = container.scrollHeight
    },

    formatMessage(content) {
      if (content === undefined || content === null) return '';
      // 将换行符转换为<br>标签
      return content.replace(/\n/g, '<br>');
    },

    getCookie(name) {
      const value = `; ${document.cookie}`
      const parts = value.split(`; ${name}=`)
      if (parts.length === 2) return parts.pop().split(';').shift()
      return null
    },

    shouldShowDate(index) {
      if (index === 0) return true;
      return this.messages[index].date !== this.messages[index - 1].date;
    }
  }
}
</script>

<style scoped>
.chat-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #f5f7fa;
}

.chat-header {
  background-color: #fff;
  padding: 15px 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-content {
  display: flex;
  align-items: center;
  gap: 10px;
  font-size: 18px;
  font-weight: 500;
  color: #303133;
}

.header-content i {
  font-size: 24px;
  color: #409EFF;
}

.connection-status {
  font-size: 14px;
  color: #909399;
  padding: 4px 12px;
  border-radius: 12px;
  background-color: #f4f4f5;
}

.connection-status.connected {
  color: #67C23A;
  background-color: #f0f9eb;
}

.chat-content {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.message-wrapper {
  display: flex;
  gap: 12px;
  max-width: 80%;
}

.user-message {
  margin-left: auto;
  flex-direction: row-reverse;
}

.message-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background-color: #ecf5ff;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}

.user-message .message-avatar {
  background-color: #409EFF;
  color: #fff;
}

.ai-message .message-avatar {
  background-color: #67C23A;
  color: #fff;
}

.message-content {
  background-color: #fff;
  padding: 12px 16px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.user-message .message-content {
  background-color: #409EFF;
  color: #fff;
}

.message-text {
  font-size: 14px;
  line-height: 1.6;
  word-break: break-word;
}

.message-time {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}

.user-message .message-time {
  color: #e6e6e6;
}

.chat-input {
  background-color: #fff;
  padding: 20px;
  box-shadow: 0 -2px 12px 0 rgba(0, 0, 0, 0.1);
  display: flex;
  gap: 12px;
  margin-top: -20px;
}

.chat-input .el-textarea {
  flex: 1;
}

.chat-input .el-button {
  align-self: flex-end;
  padding: 12px 24px;
}

.typing-indicator {
  display: flex;
  gap: 4px;
  padding: 8px 0;
}

.typing-indicator span {
  width: 8px;
  height: 8px;
  background-color: #909399;
  border-radius: 50%;
  animation: typing 1s infinite ease-in-out;
}

.typing-indicator span:nth-child(2) {
  animation-delay: 0.2s;
}

.typing-indicator span:nth-child(3) {
  animation-delay: 0.4s;
}

@keyframes typing {
  0%, 100% {
    transform: translateY(0);
  }
  50% {
    transform: translateY(-6px);
  }
}

/* 自定义滚动条样式 */
.chat-content::-webkit-scrollbar {
  width: 6px;
}

.chat-content::-webkit-scrollbar-track {
  background: #f5f7fa;
}

.chat-content::-webkit-scrollbar-thumb {
  background: #dcdfe6;
  border-radius: 3px;
}

.chat-content::-webkit-scrollbar-thumb:hover {
  background: #c0c4cc;
}

.date-divider {
  text-align: center;
  color: #909399;
  font-size: 13px;
  margin: 10px 0;
}
</style> 